﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class PurchaseOrderPaymentManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["PurchaseOrderID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["PurchaseOrderID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblPurchaseOrderID.Text = Request.QueryString["PurchaseOrderID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据


                //给日期输入框添加只读属性，不能在属性里直接设置，不然会取不到值
                this.txtDateReckoning.Attributes["readonly"] = "true";
                this.txtDateReckoning.Date = System.DateTime.Now;
                //设置经办人
             Accounts_Users currentUser =mk.l.Accounts_Users.FirstOrDefault();
                this.lblManagerTrueName.Text = currentUser.TrueName;
                this.lblManagerUserName.Text = currentUser.UserName;
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(j => j.ClassID == (int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                this.BindAccountID();
                this.ShowCurrentBalance();
                this.lblInfoFrom.Text = "本公司";
                this.BindData();
            }
        }
           /// </summary>
        private void BindAccountID()
        {
            var bll = mk.l.Sales_Account.ToList();
           var ds = bll.Where(y=>y.RootDepartmentID.ToString()== this.lblRootDepartmentID.Text);
            this.ddlAccountID.DataSource = ds;
            this.ddlAccountID.DataTextField = "Name";
            this.ddlAccountID.DataValueField = "AccountID";
            this.ddlAccountID.DataBind();
        }

        /// <summary>
        /// Binds the data.绑定页面基本数据
        /// </summary>
        private void BindData()
        {
            var bllPurchaseOrderHeader = mk.l.Sales_PurchaseOrderHeader.ToList();
                ;
           Sales_PurchaseOrderHeader mPurchaseOrderHeader = bllPurchaseOrderHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
            if (mPurchaseOrderHeader != null)
            {
                //判断是否是本店的订单
                if (int.Parse(this.lblRootDepartmentID.Text) == mPurchaseOrderHeader.RootDepartmentID)
                {
                    if (mPurchaseOrderHeader.StatusPayment == "0")
                    {
                        if (mPurchaseOrderHeader.SubTotal > 0)
                        {
                            //显示订货单数据
                            this.lblPurchaseOrderNumber.Text = mPurchaseOrderHeader.OrderNumber;
                            //显示收款方信息
                       var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
                    Sales_Manufacturer mManufacturer = bllManufacturer.Where(h=>h.ManufacturerID==mPurchaseOrderHeader.ManufacturerID).FirstOrDefault();
                            if (mManufacturer != null)
                            {
                                this.lblInfoTo.Text = mManufacturer.ManufacturerName + ":" + mManufacturer.BankAccount;
                            }
                            this.txtSettlementAmount.Text = mPurchaseOrderHeader.SubTotal.ToString();
                        }
                        else
                        {
                           mk.Alert("还未设置成本价格！请设置价格后再进行付款操作");
                        }
                    }
                    else
                    {
                       mk.Alert("此订货单已经付款完毕！");
                    }
                }
                else
                {
                   mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！");
            }
        }

        /// <summary>
        /// 处理订货单付款
        /// </summary>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.IsValid)   //进行页面验证
            {
                //实例化订货单表头业务逻辑类
             var bllPurchaseOrderHeader = 
                   mk.l.Sales_PurchaseOrderHeader.ToList();
                //根据订货单ID号得到订货单实体类
  Sales_PurchaseOrderHeader mPurchaseOrderHeader = 
                    bllPurchaseOrderHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
                if (mPurchaseOrderHeader != null)
                {
                    //如果订货单处于未付款状态
                    if (mPurchaseOrderHeader.StatusPayment == "0")
                    {
                        //实例化付款详细列表业务逻辑类
                      var bll = 
                            mk.l.Sales_SettlementDetail.ToList();
                        //实例化付款列表实体类
                    Sales_SettlementDetail m = 
                           new Sales_SettlementDetail();
                        //得到用户选择的账户ID
                        m.AccountID = int.Parse(this.ddlAccountID.SelectedValue);
                        //获取付款日期
                        m.DateReckoning = Convert.ToDateTime(this.txtDateReckoning.Date);
                        m.Flag = "1";
                        m.InfoFrom = this.lblInfoFrom.Text;
                        m.InfoTo = this.lblInfoTo.Text;
                        m.Manager = this.lblManagerUserName.Text;
                        m.ModifiedDate = System.DateTime.Now;
                        m.Notes = mk.InputText(this.txtNotes.Text, 200);
                        m.PurchaseOrderID = int.Parse(this.lblPurchaseOrderID.Text);
                        m.RootDepartmentID = int.Parse(this.lblRootDepartmentID.Text);
                        m.SalesOrderID = 0;
                        //金额设置为负值
                        m.SettlementAmount = -decimal.Parse(this.txtSettlementAmount.Text);
                        //购买原材料付款的类别ID为1
                        m.TypeID = 1;
                        try
                        {
                          //  bll.Add(m);
                            mk.l.Sales_SettlementDetail.InsertOnSubmit(m);
                            mk.l.SubmitChanges();
                            //更新账户的信息
                          var bllAccount = 
                              mk.l.Sales_Account.ToList();
                            //得到指定账户ID的账户对象
              Sales_Account mAccount = 
                                bllAccount.Where(h=>h.AccountID==int.Parse(this.ddlAccountID.SelectedValue)).FirstOrDefault();
                            //扣减账户余额
                            mAccount.Balance -= decimal.Parse(this.txtSettlementAmount.Text);
                          //  bllAccount.Update(mAccount);
                            mk.l.SubmitChanges();
                            //更改订货单的付款状态付款时间
                            var bllHeader =
                                        mk.l.Sales_PurchaseOrderHeader.ToList();
                          Sales_PurchaseOrderHeader mHeader = 
                                bllHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
                            mHeader.StatusPayment = "1";
                            mHeader.DatePayment = Convert.ToDateTime(this.txtDateReckoning.Date);
                            mHeader.ModifiedDate = System.DateTime.Now;
                          //  bllHeader.Update(mHeader);
                            mk.l.SubmitChanges();
                            //提交事务
                         //   ContextUtil.SetComplete();
                           mk.Alert("付款成功！");
                        }
                        catch (Exception ex)
                        {
                            //撤销事务
                         //   ContextUtil.SetAbort();
                           mk.Alert("付款失败！错误信息：" + ex.Message);
                        }
                    }
                    else
                    {
                       mk.Alert("此订货单已经付款完毕！");
                    }
                }
                else
                {
                   mk.Alert("参数错误！此订货单不存在或已被删除");
                }
            }
        }

        /// <summary>
        /// Shows the current balance.
        /// </summary>
        private void ShowCurrentBalance()
        {
            if (this.ddlAccountID.SelectedValue != "")
            {
              var bll = mk.l.Sales_Account.ToList();
          Sales_Account m = bll.Where(h=>h.AccountID==int.Parse(this.ddlAccountID.SelectedValue)).FirstOrDefault();
                this.lblCurrentBalance.Text = m.Balance.ToString();
            }
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlAccountID control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ddlAccountID_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ShowCurrentBalance();
        }
    }
}

